package com.itheima.reggie.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.Page;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Result;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    public EmployeeMapper employeeMapper ;

    public Result<Employee> login(  Employee employee ){
        Employee login = employeeMapper.login(employee);
        if(StrUtil.isBlank(employee.getUsername())){
            return Result.error("输入用户名不能为空");
        }
        if(login == null ){
            return Result.error("没有该用户");
        }
        if( !StrUtil.equals( login.getPassword() , SecureUtil.md5(employee.getPassword()))){
            return Result.error("密码错误");
        }
        if(login.getStatus() != 1 ){
            return Result.error("该用户以禁用");
        }
        login.setPassword(null);
        return Result.success(login);
    }

    //添加员工
    @Override
    public Result add(Employee employee) {
        employee.setPassword(SecureUtil.md5("123456"));
        employee.setStatus(1);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employeeMapper.add(employee);
        return Result.success(null);

    }

    @Override
    public Page<Employee> page(Integer page, Integer pageSize, String name) {
        PageHelper.startPage(page , pageSize );
        //使用pageHelper
        //查询数据
        List<Employee> page1 = employeeMapper.page(name);
        PageInfo<Employee> employeePageInfo = new PageInfo<>(page1);
        Page<Employee> employeePage = new Page<>();
        employeePage.setRecords(employeePageInfo.getList());
        employeePage.setTotal(employeePageInfo.getTotal());
        return employeePage;
    }

    //修改状态
    @Override
    public void updateStatus(Employee employee) {
        employee.setUpdateTime( LocalDateTime.now() );
        employeeMapper.updateStatus(employee);
    }

    //编辑用户
    @Override
    public Employee updateEmployee(Long id) {
        return null;
    }

    //编辑员工数据回显
    @Override
    public Employee findById(Long id) {
       return employeeMapper.findById( id );
    }

}
